package kr.or.javacafe.cw.web.bokjiro;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.sql.DataSource;

import kr.or.javacafe.cw.common.vo.Resource;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;



public class BokjiroProcessor implements ItemProcessor<Resource, Resource> {

	static Logger logger = LoggerFactory.getLogger(BokjiroProcessor.class);
	
	private JdbcOperations jdbcTemplate;
	
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	
	
	public Resource process(Resource res) throws Exception {
		
		try {
			
			String query = res.getSource();

			HttpClient httpClient = new HttpClient();
			HttpMethod method = new GetMethod(query);
			
			int status = httpClient.executeMethod(method);
			if (200 == status) {
				
				//String strXML = new String(method.getResponseBody(), "UTF-8");
				
				StringBuffer resultMessage = new StringBuffer();
				
				BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), "utf-8"));
				String line;
			    while ((line = br.readLine()) != null) {
			    	resultMessage.append(line);
			    }
			    br.close();
				
				String strHTML = resultMessage.toString();

				logger.debug("======================================================================================");
				logger.debug(query);
				logger.debug("======================================================================================");

				Document doc = Jsoup.parse(strHTML);
				Elements elements = doc.select("#realCont");
				
				res.setRawData(elements.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return res;
	}

}
